package com.java.shop.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 解决Feign远程调用时会丢失请求头信息（因为每次远程调用都是创建的一个新的请求信息）
 */
@Configuration
public class ShopFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate requestTemplate) {
                /* RequestContextHolder拿到刚进来的这个请求 */
                ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                if(attributes != null){
                    HttpServletRequest request = attributes.getRequest();
                    /* 同步头信息中的cookie */
                    if(request != null){
                        requestTemplate.header("Cookie",request.getHeader("Cookie"));
                    }
                }
            }
        };
    }
}
